import Vue from "vue";
import Router from "vue-router";
import Home from "@/components/Home/home.vue";
import Cart from "@/views/Cart.vue";
import Category from "@/views/Category.vue";
import User from "@/views/User.vue";
Vue.use(Router);

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const router = new Router({
  mode: "history",
  // base: process.env.BASE_URL,
  base:'shop',
  routes: [
    { path: "/", redirect: "/home" }, //路由重定向
    // 首页
    {
      path: "/home",
      name: "Home",
      meta: {
        isShowTabbar: true,
      },
      component: Home,
      children: [
        {
          path: "popup",
          name: "popup",
          component: () => import("@/components/Popup/popup.vue"),
        },
      ],
    },
    //专题
    {
      path: "/topic",
      meta: {
        isShowTabbar: true,
      },
      component: () => import("@/views/Topic.vue"),
    },
    //分类
    {
      path: "/category",
      meta: {
        isShowTabbar: true,
      },
      component: () => import("@/views/Category.vue"),
    },
    //购物车
    {
      path: "/cart",
      meta: {
        isShowTabbar: true,
      },
      component: () => import("@/views/Cart.vue"),
    },
    //我的
    {
      path: "/user",
      meta: {
        isShowTabbar: true,
      },
      component: () => import("@/views/User.vue"),
    },
    // 商品明细
    {
      path: "/detal",
      component: () => import("@/components/detal/detal.vue"),
    },
  ],
});

export default router;

//路由前置守卫 当用户点击购物车先判断是否有token权限才可以进入
router.beforeEach((to, from, next) => {
  let token = window.sessionStorage.getItem("token");
  //登录的是购物车的话判断是否带了token
  if (to.path == "/cart") {
    if (token) {
      next();
    } else {
      Vue.prototype.$toast.fail("请先登录");
      setTimeout(() => {
        next("user");
      }, 400);
    }
    return;
  }

  next();
});
